<template>
    <div class="app-container" v-loading="loading">
        <el-card>
            <template #header>
                <div class="head-container flexC">
                    <p class="title">项目详情</p>
                    <div>
                        
                        <el-button @click="downloadProject(null,1)"  :loading="downloading" type="primary" :icon="Download">下载</el-button>
                        <el-button @click="handleAI"   type="primary" >
                            <template #icon >
                                <el-icon>
                                    <svg-icon name="ai" /> 
                                </el-icon>
                            </template>
                            AI处理
                        </el-button>
                        <el-button type="primary" :icon="Back" plain  @click="back">返回</el-button>
                    </div>
                </div>
            </template>
            <el-form label-width="100px" style="width: 100%;" label-position="left">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="项目名称">
                             {{detailObj?.name}}
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="创建时间">
                             {{ detailObj.ct ? moment(detailObj.ct).format('YYYY-MM-DD HH:mm:ss') : '--' }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="存储位置">
                            <el-tooltip :content="detailObj.cabinetRemark" :disabled="!detailObj.cabinetRemark">
                                {{detailObj.cabinetBoxNames||'--'}}
                            </el-tooltip>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="处理进度">
                            <el-tag v-if="detailObj.sysState" :type="projectProcess[detailObj.sysState]?.type">
                                {{ projectProcess[detailObj.sysState]?.text }}
                            </el-tag>
                            <span v-else>--</span>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
           <!-- 项目要点 -->
        <EditMainPoint ref="editMainPointRef" :detail="detailObj" @close="getDetails"></EditMainPoint>
        <el-card style="margin-top: 15px;">
            <template #header>
                <div class="head-container flexC">
                    <p class="title">
                        图像列表<span class="sub-title">请先安装并打开扫描仪和高拍仪</span>
                    </p>
                    <div class="flexC">
                        <!-- <p style="margin-right: 10px;">导入文件 <el-icon><DArrowRight /></el-icon></p> -->
                        <el-tooltip content="点击启动扫描仪" >
                            <el-button type="primary" plain :icon="Plus" @click="handleScanner">扫描仪</el-button>
                        </el-tooltip>
                        <el-tooltip content="启动高拍仪" >
                            <el-button type="success" plain @click="go('/projectDigital/highSpeedScanner')" :icon="Plus">高拍仪</el-button>
                        </el-tooltip>
                        <el-tooltip content="导入本地图像" >
                            <el-button type="warning" plain :icon="Plus" @click="exportFile">本地导入</el-button>
                        </el-tooltip>
                    </div>
                </div>
            </template>
             <el-table :data="taskTable"   stripe style="width: 100%"
                :header-cell-style="headerStyle"
                :cell-style="cellStyle"
            >
                <el-table-column prop="name" label="图像名称" min-width="160" show-overflow-tooltip/>
                <el-table-column prop="source" label="数据来源" min-width="160"  >
                    <template #default="scope">
                        {{ projectSource[scope.row.source] || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="state" label="上传状态" min-width="120">
                    <template #default="scope">
                        <div v-if="scope.row.dealState">
                            <el-tag :type="projectUpdateStatus[scope.row.dealState]?.type">{{projectUpdateStatus[scope.row.dealState]?.text}}</el-tag>
                        </div>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column prop="pageCount" label="页数" min-width="120"/>
                <el-table-column prop="state" label="标记状态" min-width="200">
                    <template #default="scope">
                        <div v-if="scope.row.state">
                            <!-- <el-tag :type="scope.row.mark != 0?'success':''">{{ scope.row.mark == 0 ? '未标记' : '已标记' }}</el-tag> -->
                            <el-tag :type="projectStatus[scope.row.state]?.type">{{projectStatus[scope.row.state]?.text}}</el-tag>
                        </div>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column prop="finishTime" label="操作" width="280" fixed="right" align="center">
                    <template #default="scope">
                        <el-button type="primary"  link @click="handleTags(scope.row,1)">整体标记</el-button>
                        <el-button type="primary" link @click="handleTags(scope.row,2)">分拆标记</el-button>
                        <!-- <el-button type="primary" link @click="preView({fileId:scope.row.id})">预览</el-button> -->
                        <el-button type="danger" link  :loading="scope.row.loading" :disabled="scope.row.state == 'Processed'" @click="deleteTask(scope.row)">删除</el-button>
                        
                    </template>
                </el-table-column>
             </el-table>
        </el-card>
        <el-card>
            <template #header>
                <div class="head-container flexC">
                    <p class="title">文件列表</p>
                </div>
            </template>
            <el-table :data="fileTable" stripe style="width: 100%"
                :header-cell-style="headerStyle"
                :cell-style="cellStyle"
            >
                <el-table-column prop="title" label="文件名称" min-width="160" show-overflow-tooltip/>
                <el-table-column prop="cabinetNames" label="存储位置" min-width="160" show-overflow-tooltip />
                <el-table-column prop="source" label="标记方式" min-width="120"  >
                    <template #default="scope">
                        {{ projectSource[scope.row.source] || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="pageCount" label="页数" min-width="120"/>
                <el-table-column prop="tagTime" label="标记时间" min-width="200">
                    <template #default="scope">
                        {{ scope.row.tagTime? moment(scope.row.tagTime).format('YYYY-MM-DD HH:mm:ss') : '--' }}
                    </template>
                </el-table-column>  
                <el-table-column prop="finishTime" label="操作" width="250" fixed="right" align="center">
                    <template #default="scope">
                        <el-button type="primary" link @click="handleTags(scope.row,3)">预览</el-button>
                        <el-button type="primary" link  @click="downloadProject(scope.row,2)">下载</el-button>
                    </template>
                </el-table-column>
             </el-table>
        </el-card>
        <local-export @close="close" ref="localExportRef"></local-export>
        <set-tags @close="close" ref="setTagsRef" ></set-tags>
        <splictTags @close="close" ref="splictTagsRef"></splictTags>

        <div v-if="AILoading" class="loading-container flexCC el-loading-mask is-fullscreen">
            <div class="container">
                <div class="loading-icon" >
                    <img src="@/assets/images/AIload.gif" alt="">
                </div>
                <p class="text">{{ AILoadingMsg }}</p>
            </div>
        </div>
    </div>
</template>

<script setup>
import { Back, DArrowRight, Plus, Download } from '@element-plus/icons-vue';
import { projectSource } from '@/utils/static';
import { onMounted, onUnmounted, ref, getCurrentInstance } from 'vue';
import { ProjectDetails, ProjectTaskQuery, ProjectFileQuery, ProjectTaskDelete, ProjectTaskScanner, delPwConfirm, ProjectTaskImages, taskProjectAI, taskProgress } from "@/api/project";
import { useRoute, useRouter } from 'vue-router';
import localExport from './components/local_export.vue';
import setTags from './components/fileTags.vue';
import splictTags from './components/splictTags.vue';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import { DownloadAdd } from "@/api/user";
import moment from 'moment';
import { projectProcess, projectStatus, projectUpdateStatus } from "@/utils/static";
import EditMainPoint from './components/EditMainPoint.vue';
import { MD5 } from 'crypto-js'

const { proxy } = getCurrentInstance();
const loading = ref(false);
const AILoading = ref(false);
const AILoadingMsg = ref("");
const downloading = ref(false);
const localExportRef = ref(null);
// 项目要点 Ref
const editMainPointRef = ref(null);
const setTagsRef = ref(null);
const splictTagsRef = ref(null);

const taskLoading = ref(false);
const fileLoading = ref(false);
const router = useRouter();
const route = useRoute();
const taskTable = ref([]);
const fileTable = ref([]);
const detailObj = ref({});

const timer = ref(null);
onMounted(() => {
    getDetails();
    getFileData();
    close();
    timer.value = setInterval(() => {
        getTaskQuery();
    },3000)
});
onUnmounted(() => {
    clearInterval(timer.value);
    sessionStorage.removeItem('Router_AddProject');
})
const go = ()=>{
    router.push({
        path: '/projectDigital/highSpeedScanner',
        query: { id: route.query.id }
    })
}
const getDetails = async () => {
    loading.value = true;
    const res = await ProjectDetails({
        id: route.query.id
    });
    loading.value = false;
    if(res.errorCode == 0){
        detailObj.value = res.data;
    }
}
const back = () => {
    if(sessionStorage.getItem('Router_AddProject') == 1){
        router.go(-2);
    }else{
        router.go(-1);
    }
}
// 获取 任务 列表
const getTaskQuery = async () => {
    taskLoading.value = true;
    const res = await ProjectTaskQuery({
        projectId: route.query.id,
    });
    taskLoading.value = false;
    if(res.errorCode == 0){
        taskTable.value = res.data;
    }
}
// AI 处理
const  handleAI =async () => {
    const loading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)',
    });
    let  result = await taskProjectAI({
        projectIds:[route.query.id]
    });
    if(result.errorCode == 0){
        processAI(result.data.id)
        AILoadingMsg.value = result.data.toast;
        AILoading.value = true;
    }
    loading.close();
}

// Ai 进度
const processAI = async (taskId)=>{
    let  result = await taskProgress({
        taskId:taskId
    });
    if(result.errorCode == 0){
        if(result.data.all != result.data.progress){
            setTimeout(()=>{
                processAI(taskId)
            },2000)
        }else{
            AILoadingMsg.value = "";
            AILoading.value = false;
            ElMessage.success('AI处理成功');
            editMainPointRef.value.getMainPointData();
            close();
        }
    }
}

const getFileData = async () => {
    fileLoading.value = true;
    let res = await ProjectFileQuery({
        projectId: route.query.id
    });
    fileLoading.value = false;
    if(res.errorCode == 0){
        fileTable.value = res.data;
    }
}
const handleTags = (row, type) => {
    if(row.dealState != 'Processed' && (type == 1 || type == 2)){
        return ElMessage.warning('文件处理中，请稍后再试');
    }
    if(type == 1){
        // 整体标记
        setTagsRef.value.open({id: row.id, type});
    }else if(type == 2 || type == 3){
        // 分拆标记
        splictTagsRef.value.open({ ...row, type});
    }
}
const preView = async (row) => {
    const loading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    let res = await ProjectTaskImages({
        ...row,
        projectId: route.query.id
    })
    loading.close();
    if(res.errorCode == 0){
        // console.log(res.data.map(item => item.imgPath));
        proxy.$ViewerApi(res.data.map(item => {return item.imgPath}));
    }

}

const exportFile = () => {
    localExportRef.value.open();
}
const close = () => {
    getDetails();
    getTaskQuery();
    getFileData();
}
// 调用 扫描仪
const handleScanner =async () => {
    const res = await ProjectTaskScanner({
        id: route.query.id
    });
}
const deleteTask = async (row) => {
    if(row.dealState != 'Processed'){
        return ElMessage.warning('文件上传中，请稍后再试');
    }
    ElMessageBox.prompt('请输入删除密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type:"warning",
        inputPattern:/^.*\S+.*$/,
        inputPlaceholder: '请输入密码',
        inputErrorMessage: '请输入密码',
        inputType: 'password',
    }).then(async({ value }) => {
        const loading = ElLoading.service({
            lock: true,
            text: '加载中...',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        let res1 = await delPwConfirm(MD5(value).toString());
        if(res1.errorCode == 0){
            const res = await ProjectTaskDelete({
                id: row.id
            });
            if(res.errorCode == 0){
                ElMessage.success('删除成功');
                getTaskQuery();
                getFileData();
            }
        }
        loading.close();
    })
}


// 用 defineOptions 定义组件选项（模拟选项式 API 的路由守卫）
defineOptions({
  // 组件内路由守卫：进入前
  beforeRouteEnter(to, from, next) {
    // console.log('beforeRouteEnter 执行');
    // console.log(to, from, 'nextfffff');
    
    // 通过 next(vm => {}) 访问组件实例
    next();
  },
  // 组件内路由守卫：参数更新
  beforeRouteUpdate(to, from, next) {
    // console.log('beforeRouteUpdate 执行');
    next();
  },
  // 组件内路由守卫：离开前
  beforeRouteLeave(to, from, next) {
    // console.log('beforeRouteLeave 执行',to, from);
    // console.log(to, from, 'nextfffff');

    next();
  }
});
// 下载 项目 zip
const downloadProject = async (item,type) => {
    if(item){
        item.downloading = true;
    }else{
        downloading.value = true;
    }
    let restult = await DownloadAdd({type:type == 1 ? 'project' : 'document', obj:type == 1 ? route.query.id : item.id});
    if(item){
        item.downloading = false;
    }else{
        downloading.value = false;
    }
    if(restult.errorCode == 0){
        ElMessage.success('下载成功,请在下载中心查看');
    }
}
</script>

<style lang="scss" scoped>
.head-container {
    justify-content: space-between;
    .title{
        font-weight: 600;
        font-size: 18px;
        .sub-title{
            font-size: 12px;
            color: var(--el-color-warning);
            margin-left: 15px;            
        }
    }
}
:deep(.el-form-item__label){
    
}
.loading-container{
    background-color: rgba(0, 0, 0, 0.7) !important;
    z-index: 1000000;
    .container{
        width: 50%;
        .loading-icon{
            // width: ;
            display: block;
            text-align: center;
            height: 180px;
            margin-bottom: -10px;
            background: none;
            img{
                height: 100%;
            }
            // :deep(.el-loading-mask){
            //     background: none;
            // }
        }
        .txt{
            color: #fff; 
        }
        .text{
            text-align: center;
            color: var(--el-color-primary);
            margin-bottom: 20px;
            font-size: 18px;
        }
    }
}
</style>